const app = getApp()
let username = ''
let secretKey = ''
let newPassword = ''

Page({
  data: {
    showModalStatus: false,
  }, 
  username(event) {
    username = event.detail.value
    console.log("username", username)
  },
  secretKey(event) {
    secretKey = event.detail.value
    console.log("secretKey", secretKey)
  },
  newPassword(event) {
    newPassword = event.detail.value
    console.log("newPassword", newPassword)
  },
  checkAndSubmit: function (e) {
    if (!username || !secretKey || !newPassword) {
      this.showToast('输入部分不能为空');
      this.update({currentTarget: {dataset: {statu:"close"}}});
      return;
    }
    let username2 = this.shiftString(username)
    let secretKey2 = this.shiftString(secretKey)
    let newPassword2 = this.shiftString(newPassword)

    let userInfo = wx.getStorageSync('userInfo')
    let shiftedUsername = wx.getStorageSync('userName')
    let shiftedSecretKey = wx.getStorageSync('shiftedString')

    if(username2 !== shiftedUsername){
      this.showToast('本机账号有误');
      this.update({currentTarget: {dataset: {statu:"close"}}});
      return;
    }

    if(newPassword2 !== shiftedSecretKey){
      this.showToast('本机密钥有误');
      this.update({currentTarget: {dataset: {statu:"close"}}});
      return;
    }

    let oldPassword = userInfo.password

    this.sendUpdateRequest(username2, oldPassword, newPassword2);
  },
  shiftString: function (str){
    let shiftedStr = '';
    for (let i = 0; i < str.length; i++) {
      let shiftedChar = String.fromCharCode(str.charCodeAt(i) + 2);
      shiftedStr += shiftedChar;
    }
    return shiftedStr;
  },
  showToast: function(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    });
  },
  sendUpdateRequest: function(username2, oldPassword, newPassword2) {
    wx.request({
      url: '/update',
      method: 'POST',
      data: {
        nickname: username2,
        password: oldPassword,
        newPassword: newPassword2
      },
      success: (res) => {
        if (res.data.code == 200) {
          this.showToast("密码更改成功,请重新登陆");
          this.update({currentTarget: {dataset: {statu:"close"}}});
        } else {
          this.showToast(res.data.message);
        }
      }
    });
  },
})